package org.bigmarketapi.projectreview.LUA;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RScript;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @BelongsProject: ProjectReview
 * @BelongsPackage: org.bigmarketapi.projectreview.LUA
 * @Author: dujiaqi
 * @CreateTime: 2024-11-16  22:45
 * @Description: TODO
 * @Version: 1.0
 */
@Service
@Slf4j
public class LuaService {
    @Resource
    activityDao dao;
    @Resource
    RedissonClient redisson;

    public Object inBatches() {
        final RScript rScript = redisson.getScript();
        final activity activity = dao.queryActivity();
        String basicPath = "/Users/dujiaqi/Desktop/营销/Big-market/ProjectReview/src/main/java/org/bigmarketapi/projectreview/LUA/Script/";
        //todo: lua脚本的参数类型均设置成String，方便稳妥。类型转换等放在lua脚本实现
        List<Object> keys = Arrays.asList("stockMap");
        //将其他属性转成数组
        final Object eval = rScript.eval(
                RScript.Mode.READ_WRITE,
                getScriptContent(basicPath + "paramsCheck.lua"),
                RScript.ReturnType.MULTI,
                keys,
              activity.getStockId(),activity.getCouponId(),activity.getUid(),activity.getMaxByDay(),activity.getMaxByUser(),activity.getCrtDate().getTime(),activity.getDailyMaxByUser());
        log.info("eval: {}", eval);
        return eval;
    }

    private String getScriptContent(String scriptPath) {
        try {
            final byte[] encoded = Files.readAllBytes(Paths.get(scriptPath));
            return new String(encoded, "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

